package com.hl.card.award.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hl.card.common.persistence.dao.DisMemberApplyMapper;
import com.hl.card.modular.pack.service.UserDataService;
import com.hl.card.modular.packBack.service.GoodsSevice;
import com.hl.card.modular.packBack.service.ISalesDivisionService;
import com.hl.card.award.service.IRewardByTrans;
import com.hl.card.award.service.ITrainRewardByTrans;
import com.hl.card.common.persistence.model.Goods;
import com.hl.card.common.remote.user.RemoteUser;
import com.hl.card.common.remote.user.RemoteUserService;
import com.hl.card.common.util.ResponseObject;
import com.hl.card.common.util.PayUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * java类简单作用描述
 *
 * @ProjectName: distdev
 * @Package: com.hl.card.modular.pack.service.impl
 * @ClassName: ${TYPE_NAME}
 * @Description: java类作用描述
 * @Author: 作者姓名
 * @CreateDate: 2018/7/9 17:41
 * @UpdateUser: Neil.Zhou
 * @UpdateDate: 2018/7/9 17:41
 * @UpdateRemark: The modified content
 * @Version: 1.0
 * <p>Copyright: Copyright (c) 2018</p>
 */
@Service
public class TrianRewardByTransImpl implements ITrainRewardByTrans {

    private static final Logger logger = LoggerFactory.getLogger(TrianRewardByTransImpl.class);
    @Autowired
    private PayUtils payUtils;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RemoteUserService remoteUserService;

    @Autowired
    private UserDataService userDataService;

    @Autowired
    ISalesDivisionService iSalesDivisionService;

    @Resource
    private GoodsSevice goodsSevice;

    @Autowired
    private IRewardByTrans rewardByTrans;

    @Value("${dismemberapply.ka_ip}")
    private String cpc_ip;

    public ResponseObject getCurrTrainCode(String parentCode) {
        ResponseObject res = new ResponseObject();
        Map map = new HashMap<>();
        String code = "0";
        String WJ_code = rewardByTrans.getCurrCode(parentCode);
        //String WJ_code = stringRedisTemplate.opsForValue().get("CURR_"+ parentCode + "_CODE");
        if(StringUtils.isBlank(WJ_code)) {
            map.put("code", "5");
            map.put("paperCode", "");
            map.put("msg", "无答题码");
        }else {
            Goods goods = goodsSevice.selectByCode(parentCode);
            String prodName = "undefined";
            if(goods != null) {
                prodName = goods.getGoodsName();
                if(StringUtils.isBlank(prodName)) {
                    map.put("code", "5");
                    map.put("paperCode", "");
                    map.put("msg", "无答题码");
                }else {
                    map.put("code", "0");
                    map.put("paperCode", WJ_code);
                    map.put("msg", "获取成功");
                }
            }else {
                map.put("code", "5");
                map.put("paperCode", "");
                map.put("msg", "无答题码");
            }
        }

        System.out.println("获取当前答题码：" + WJ_code);
        return res;
    }

    public ResponseObject getCurrTrainConfig(String parentCode) {
        String curr_code = rewardByTrans.getCurrCode(parentCode);
        return getTrainConfig(parentCode, curr_code);
        //return getTrainConfig(parentCode, stringRedisTemplate.opsForValue().get("CURR_"+ parentCode + "_CODE"));
    }

    public ResponseObject getTrainConfig(String parentCode, String prodCode) {
        ResponseObject res = new ResponseObject();
        Map map = new HashMap<>();
//		String repeatCount = rest.get("count");
        if(StringUtils.isBlank(prodCode)) {
            map.put("code", "6");
            map.put("prodName", "");
            map.put("count", 0);
            map.put("statue", "0");
            map.put("msg", "当前试卷码为空");
            System.out.println("getTrainConfig:当前试卷码为空");
            res.setData(map);
            res.setErroCode(1);
            return res;
        }
        String code = "0";
        Goods goods = goodsSevice.selectByCode(parentCode);
        String prodName = "undefined";
        if(goods != null) {
            prodName = goods.getGoodsName();
            if(StringUtils.isBlank(prodName)) {
                code = "4";
            }
        }else {
            code = "4";
        }
        String paper = stringRedisTemplate.opsForValue().get(prodCode);
        if(StringUtils.isBlank(paper)) {
            code = "5";
        }
        if("4".equals(code)) {
            map.put("code", "4");
            map.put("prodName", prodName);
            map.put("count", 0);
            map.put("statue", "0");
            map.put("msg", "该奖励在系统中不存在");
            System.out.println(prodName + "奖励在系统中不存在");
            res.setData(map);
            res.setErroCode(1);
            return res;
        }else if("5".equals(code)){
            map.put("code", "5");
            map.put("prodName", prodName);
            map.put("count", 0);
            map.put("statue", "0");
            map.put("msg", "试卷不存在");
            System.out.println(prodName + "试卷不存在");
            res.setData(map);
            res.setErroCode(1);
            return res;
        }

        Map<String,Integer> re = (Map<String,Integer>) userDataService.fraction(parentCode, Double.valueOf("100"));
        Integer member=re.get("member");//huiyuang
        Integer partner=re.get("partner");//hehuoren
        Integer bibi=re.get("bibi");//bibi
        map.put("code", "0");
        map.put("perScoreAward", member/100);
        map.put("paper", paper);
        map.put("count", "0");
        map.put("msg", "获取答题奖励配置成功");

        res.setData(map);
        res.setErroCode(0);
        System.out.println("获取答题比豆奖励标准：" + prodName + "状态：" + map.get("msg"));
        return res;
    }

    public ResponseObject currTrain(String mobile, String parentCode, String paper) {
        String curr_code = rewardByTrans.getCurrCode(parentCode);
        return train(mobile, parentCode, curr_code, paper);
        //return train(mobile, parentCode, stringRedisTemplate.opsForValue().get("CURR_"+ parentCode + "_CODE"), paper);
    }

    public ResponseObject train(String mobile, String parentCode, String prodCode, String paper) {
        ResponseObject resGetScore = getTrainScore(parentCode, prodCode, paper);
        Map map = (Map) resGetScore.getData();
        String score = "0";
        if("0".equals(map.get("code"))) {
            score = (String) map.get("score");
        }else {
            return resGetScore;
        }

        System.out.println("答题奖励：mobile=" + mobile + ";  prodCode=" + prodCode + ";  score=" + score);

        ResponseObject res = new ResponseObject();
        int sc = Integer.parseInt(score);
        if(sc > 300) {
            res.setErroCode(1);
            map.put("code", "5");
            map.put("msg", "未知错误");
            res.setData(map);
            return res;
        }
        JSONObject json = remoteUserService.findSsoUserByPhone(mobile);
        if (json.get("code").equals("0")) {
            JSONObject userObj= (JSONObject) json.get("user");
            RemoteUser remoteUser = JSON.parseObject(userObj.toJSONString(),RemoteUser.class);
            res = rewardByTrans.makeDistProfitSplitOnlyOnetime(remoteUser.getUserId(), parentCode, prodCode, score);
            //res = distProfitSplit(remoteUser.getUserId(), prodCode, score);
            if(res.getErroCode() == 0) {
                //答题成功，保存用户答题答案
                String awardKey = rewardByTrans.getAwardKey(remoteUser.getUserId(), prodCode);
                stringRedisTemplate.opsForValue().set(awardKey, paper);
            }
            map = (Map) res.getData();
            map.put("score", score);
            res.setData(map);
        }else {
            res.setErroCode(1);
            map.put("code", "2");
            map.put("msg", "用户不存在");
            res.setData(map);
        }
        return res;
    }

    /**
     * 试卷json示例
     * awardValue：试卷奖励阀值，比如中华诗词之旅要求分数100能得奖励，不足100不给予奖励
     * 外层序号：题目序号
     * 内层序号：题目标题
     * Z：为标准答案
     * num：题目数
     * value：为本题分值
     {
     "1":{
     "1":"诗词",
     "A1":"春晓|作者:王焕之",
     "B1":"春晓|作者：王焕之",
     "C1":"春晓|作者：王焕之",
     "D1":"春晓|作者：王焕之",
     "F1":"春晓|作者：王焕之",
     "E1":"春晓|作者：王焕之",
     "Z":"A1",
     "value":50
     },
     "2":{
     "2":"诗词句",
     "A":"春眠不觉晓",
     "B":"疑似地上霜",
     "C":"处处闻啼鸟",
     "D":"低头思故乡",
     "E":"夜来风雨声",
     "F":"烟花三月下扬州",
     "G":"花落知多少",
     "H":"谁知盘中餐",
     "J":"粒粒皆辛苦",
     "Z":"ACEG",
     "value":50
     },
     "num":2,
     "awardValue":"100"
     "poetry":"A1-春晓|作者:王焕之|A-春眠不觉晓|C-处处闻啼鸟|E-夜来风雨声|G-花落知多少",
     "photo":"https://itjh.oss-cn-beijing.aliyuncs.com/app/WJ03.jpg"
     }
     */
    public ResponseObject getTrainScore(String parentCode, String prodCode, String paper) {
        String score;
        String refer_paper;
        JSONObject refer_paper_obj;
        JSONObject paper_obj;
        ResponseObject res = new ResponseObject();
        Map map = new HashMap<>();
//		String repeatCount = rest.get("count");
        String code = "0";
        if(StringUtils.isBlank(prodCode)) {
            map.put("code", "6");
            map.put("prodName", "");
            map.put("count", 0);
            map.put("statue", "0");
            map.put("msg", "当前试卷码为空");
            System.out.println("当前试卷码为空");
            res.setData(map);
            res.setErroCode(1);
            return res;
        }
        System.out.println("getTrainScore->parentCode:" + parentCode);
        Goods goods = goodsSevice.selectByCode(parentCode);
        String prodName = "undefined";
        if(goods != null) {
            prodName = goods.getGoodsName();
            if(StringUtils.isBlank(prodName)) {
                code = "4";
            }
        }else {
            code = "4";
        }
        refer_paper = stringRedisTemplate.opsForValue().get(prodCode);
        if(StringUtils.isBlank(paper)) {
            code = "5";
        }
        if("4".equals(code)) {
            map.put("code", "4");
            map.put("prodName", prodName);
            map.put("count", 0);
            map.put("statue", "0");
            map.put("msg", "该奖励在系统中不存在");
            System.out.println(prodName + "奖励在系统中不存在");
            res.setData(map);
            res.setErroCode(1);
            return res;
        }else if("5".equals(code)){
            map.put("code", "5");
            map.put("prodName", prodName);
            map.put("count", 0);
            map.put("statue", "0");
            map.put("msg", "试卷不存在");
            System.out.println(prodName + "试卷不存在");
            res.setData(map);
            res.setErroCode(1);
            return res;
        }

        if(StringUtils.isBlank(paper)) {
            map.put("code", "6");
            map.put("prodName", prodName);
            map.put("count", 0);
            map.put("statue", "0");
            map.put("msg", "提交试卷为空");
            System.out.println(prodName + "提交试卷为空");
            res.setData(map);
            res.setErroCode(1);
            return res;
        }
        paper = paper.replace("_", "-");
        System.out.println("试卷提交答案" + paper);
        String[] paper_a = paper.split("-");
        try {
            refer_paper_obj = JSONObject.parseObject(refer_paper);
        } catch (Exception e) {
            e.printStackTrace();
            map.put("code", "7");
            map.put("prodName", prodName);
            map.put("count", 0);
            map.put("statue", "0");
            map.put("msg", "试卷解析异常");
            System.out.println(prodName + "试卷解析异常");
            res.setData(map);
            res.setErroCode(1);
            return res;
        }
        int scoreInt = 0;
        JSONObject refer_temp;
        JSONObject temp;

        int size = refer_paper_obj.getIntValue("num");
        System.out.println("试卷标准答案数：" + size);
        System.out.println("试卷提交答案数：" + paper_a.length);
        if(size != paper_a.length) {
            map.put("code", "11");
            map.put("prodName", prodName);
            map.put("count", 0);
            map.put("statue", "0");
            map.put("msg", "提交答案个数少于标准答案个数，请检查");
            System.out.println(prodName + "提交答案个数少于标准答案个数");
            res.setData(map);
            res.setErroCode(1);
            return res;
        }
        for(int i = 0; i < size; i ++) {
            String index = Integer.toString(i + 1);
            String T = refer_paper_obj.getString(index);
            System.out.println("试题:" + T);
            refer_temp = JSON.parseObject(T);
            String Z = refer_temp.getString("Z");
            int value = refer_temp.getIntValue("value");
            System.out.println("试题提交答案:" + paper_a[i]);
            System.out.println("试题标准答案:" + Z);
            System.out.println("分值:" + value);
            if(Z.equals(paper_a[i].replace(" ", ""))) {
                scoreInt += value;
            }
        }
        String awardValueStr = refer_paper_obj.getString("awardValue");
        if(StringUtils.isNotBlank(awardValueStr)) {//不为空表示有奖励阀值
            int awardValue = Integer.parseInt(awardValueStr);
            if(scoreInt < awardValue) {//未达到奖励阀值，得分为0
                scoreInt = 0;
            }else {
                scoreInt = 100;//满分最多100分
            }
        }
//        if(size >= 20) {//判断题
//            for (int i = 20; i < 30; i++) {
//                String index = Integer.toString(i + 1);
//                String T = refer_paper_obj.getString(index);
//                refer_temp = JSON.parseObject(T);
//                String Z = refer_temp.getString("Z");
//                if (Z.equals(paper_a[i].replace(" ", ""))) {
//                    scoreInt += 4;
//                }
//            }
//        }

//        Map<String,Integer> re = (Map<String,Integer>) userDataService.fraction(parentCode, Double.valueOf("1.00"));
//        Integer member=re.get("member");//huiyuang
//        Integer partner=re.get("partner");//hehuoren
//        Integer bibi=re.get("bibi");//bibi
        map.put("code", "0");
        //map.put("perScoreAward", member);
        map.put("score", Integer.toString(scoreInt));
        map.put("count", "0");
        map.put("msg", "获取答题分数成功");

        res.setData(map);
        res.setErroCode(0);

        return res;
    }

    public ResponseObject checkCurrTrain(String mobile, String parentCode) {
        String curr_code = rewardByTrans.getCurrCode(parentCode);
        return checkTrain(mobile, parentCode, curr_code);
        //return checkTrain(mobile, parentCode, stringRedisTemplate.opsForValue().get("CURR_"+ parentCode + "_CODE"));
    }

    public ResponseObject checkTrain(String mobile, String parentCode, String prodCode) {
        Map map = new HashMap<>();
        ResponseObject res = new ResponseObject();
        System.out.println("checkTrain: parentCode = " + parentCode + ";  prodCode = " + prodCode);
        JSONObject json = remoteUserService.findSsoUserByPhone(mobile);
        if (json.get("code").equals("0")) {
            JSONObject userObj= (JSONObject) json.get("user");
            RemoteUser remoteUser = JSON.parseObject(userObj.toJSONString(),RemoteUser.class);
            return rewardByTrans.getAwardStatue(remoteUser.getUserId(), parentCode, prodCode);
        }else {
            res.setErroCode(1);
            map.put("code", "2");
            map.put("msg", "用户不存在");
        }
        res.setData(map);
        return res;
    }
}
